import AutoRoutes from './autoRoutes' //这个放在最前边，不多解释了
import Koa from 'koa'
import path from 'path'
import Log4js from 'koa-log4'
import logConfig from '../config/log4js' //这两行放在最上边，不解释

import {
  Nuxt,
  Builder
} from 'nuxt'


async function start() {
  const app = new Koa()
  const host = process.env.HOST || '127.0.0.1'
  const port = process.env.PORT || 3000

  // Import and Set Nuxt.js options
  const config = require('../nuxt.config.js')
  config.dev = !(app.env === 'production')

  // 生成logs目录 && 加载配置文件 start  这段放在中间位置即可
  const logger = Log4js.getLogger('app')
  const logPath = path.join(__dirname, 'logs')
  try {
    require('fs').mkdirSync(logPath)
  } catch (err) {
    if (err.code !== 'EEXIST') {
      console.error('Could not set up log directory, error was: ', err)
      process.exit(1)
    }
  }
  Log4js.configure(logConfig, {
    cwd: logPath
  })
  // 生成logs目录 && 加载配置文件 end
  //我这里把开发过程的日志去掉了，太烦躁
  if (!config.dev) {
    app.use(Log4js.koaLogger(Log4js.getLogger('http'), {
      level: 'auto'
    }))
  }


  // Instantiate nuxt.js
  const nuxt = new Nuxt(config)

  // Build in development
  if (config.dev) {
    const builder = new Builder(nuxt)
    await builder.build()
  }


  app.use(async (ctx, next) => {
    ctx.Log4js = Log4js
    await next()
  })

  AutoRoutes.auto(app) //这个放在原有的app.use前边就行了
  app.use(ctx => {
    ctx.status = 200
    ctx.respond = false // Mark request as handled for Koa
    ctx.req.ctx = ctx // This might be useful later on, e.g. in nuxtServerInit or with nuxt-stash
    nuxt.render(ctx.req, ctx.res)
  })

  app.on('error', function (err, ctx) {
    logger.error('server error', err, ctx)
  })

  app.listen(port, host)
  console.log('Server listening on ' + host + ':' + port) // eslint-disable-line no-console
}

start()
